/*
 * $Id: ApplicationListener.java 471756 2006-11-06 15:01:43Z husted $
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package trans.support;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.criterion.Restrictions;

import trans.model.User;
import trans.service.AttachmentDAO;
import trans.service.GatwayDAO;
import trans.service.SADAO;
import trans.service.SaCommentDAO;
import trans.service.UserDAO;
import trans.utils.HibernateUtil;


public final class ApplicationListener implements ServletContextListener {
    /**
     * <p>The <code>ServletContext</code> for this web application.</p>
     */
    private ServletContext context = null;
    
    /**
     * <p>Logging output for this plug in instance.</p>
     */
    private Log log = LogFactory.getLog(this.getClass());
    
    // ------------------------------------------ ServletContextListener Methods


    /**
     * <p>Gracefully shut down this database, releasing any resources that
     * were allocated at initialization.</p>
     *
     * @param event ServletContextEvent to process
     */
    public void contextDestroyed(ServletContextEvent event) {
        log.info("Finalizing memory database plug in");
        context = null;
    }


    /**
     * <p>Initialize and load our initial database from persistent
     * storage.</p>
     *
     * @param event The context initialization event
     */
    public void contextInitialized(ServletContextEvent event) {

        log.info("Initializing appliction '");
        // Remember our associated ServletContext
        this.context = event.getServletContext();
        
        log.info("Initializing services '");
        initServices();
    }


	private void initServices() {
		this.context.setAttribute(UserDAO.class.toString(), new UserDAO());
		this.context.setAttribute(GatwayDAO.class.toString(), new GatwayDAO());
		this.context.setAttribute(SADAO.class.toString(), new SADAO());
		this.context.setAttribute(SaCommentDAO.class.toString(), new SaCommentDAO());
		this.context.setAttribute(AttachmentDAO.class.toString(), new AttachmentDAO());
		
		initRootUserIfNeeded();
		
		initConfigByFile();
	}
	
	private void initConfigByFile() {
		Properties propertie = new Properties();
		try {
			propertie.load(DBManager.class.getClassLoader().getResourceAsStream(Constants.SYS_CONFIG_FILE_NAME));
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException("load config file failed");
		}
		String attachFolder = propertie.getProperty("folder.attachment");
		if(StringUtils.isEmpty(attachFolder)) throw new RuntimeException("no folder.attachment configed");
		
		Constants.CONFIG_ATTACH_FOLDER = attachFolder;
		initAttachmentFolder();
	}


	private void initAttachmentFolder() {
		File file = new File(Constants.CONFIG_ATTACH_FOLDER);
		if(file.exists() == false){
			if(file.mkdir()){
				System.out.println("System Folder Init success :"+Constants.CONFIG_ATTACH_FOLDER);
			}else{
				System.err.println("System Folder Init Fail :"+Constants.CONFIG_ATTACH_FOLDER);
			};
		}
		try {
			File stampfile = new File(Constants.CONFIG_ATTACH_FOLDER + File.separator + "stamp.txt");
			FileUtils.write(stampfile,DateFormatUtils.format( new Date(),"yyyy-MM-dd HH:mm"));
		} catch (Exception e) {
			System.out.println("initAttachmentFolder Fail :"+e.getMessage());
		}
	}


	private static void initRootUserIfNeeded(){
		if( HibernateUtil.getSession().createCriteria(User.class)
			    .add( Restrictions.eq(User.PROP_USER_ROLE, Constants.ROLE_ADMIN) )
			    .add( Restrictions.eq(User.PROP_STATUS, Constants.STATUS_ENABLE))
			    .list().isEmpty()){
			User user = new User();
			user.setUsername("root");
			user.setAddress("---");
			user.setCreateTime(new Date());
			user.setPassword("root");
			user.setStatus(Constants.STATUS_ENABLE);
			user.setUserCompName("---");
			user.setUserCode("---");
			user.setUserRole(Constants.ROLE_ADMIN);
			HibernateUtil.saveOrUpdate(user);
		}
	}
}
